package com.adgox.tiantianbiting.redpacket.share.share_for_free;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.TtbtApplication;
import com.adgox.tiantianbiting.adapter.MyShareAdapter;
import com.adgox.tiantianbiting.adapter.ShareForFreeAdapter;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.ProgramDetailBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.home.programDetail.ProgramDetailActivity;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.redpacket.share.share_detail.ShareDetailActivity;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShareForFreeActivity extends AppCompatActivity implements ShareForFreeAdapter.onItemClickListener, View.OnClickListener, MyShareAdapter.onItemClickListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.tv_my_share)
    TextView tvMyShare;

    private int chooseTab = 1;//选择tab栏，1分享免费听 2我的分享
    private int currrentPage = 1;
    private int maxPage = 10;
    private int totalPages;
    private ShareForFreeAdapter shareForFreeAdapter;
    private MyShareAdapter myShareAdapter;
    private ArrayList<ProgramDetailBean> datas = new ArrayList<>();
    private Dialog shareDialog;
    private int clickPosition;
    private int userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_for_free);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        userId = ((UserInfo) SessionManager.getDefault().getUser()).getId();
        getData();
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!rv.canScrollVertically(1)) {
                    if (currrentPage < totalPages) {
                        currrentPage++;
                        getData();
                    } else {
                        Toast.makeText(ShareForFreeActivity.this, "没有更多了", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myShareAdapter != null) {
            myShareAdapter.cancelAllCDT();
        }
    }

    @OnClick(R.id.img_finish)
    public void onFinishClicked() {
        finish();
    }

    @OnClick(R.id.tv_share)
    public void onShareClicked() {
        if (chooseTab == 1) return;
        chooseTab = 1;
        tvTitle.setText("分享免费听");
        currrentPage = 1;
        if (shareForFreeAdapter != null) {
            shareForFreeAdapter.clear();
            shareForFreeAdapter = null;
        }
        if (myShareAdapter != null) {
            myShareAdapter.clear();
            myShareAdapter = null;
        }
        datas.clear();
        tvShare.setBackgroundResource(R.drawable.bg_button_buy_all);
        tvShare.setTextColor(Color.parseColor("#FFFFFF"));
        tvMyShare.setBackground(null);
        tvMyShare.setTextColor(Color.parseColor("#353535"));
        getData();
    }

    @OnClick(R.id.tv_my_share)
    public void onMyShareClicked() {
        if (chooseTab == 2) return;
        chooseTab = 2;
        tvTitle.setText("我的分享");
        currrentPage = 1;
        if (shareForFreeAdapter != null) {
            shareForFreeAdapter.clear();
            shareForFreeAdapter = null;
        }
        if (myShareAdapter != null) {
            myShareAdapter.clear();
            myShareAdapter = null;
        }
        datas.clear();
        tvMyShare.setBackgroundResource(R.drawable.bg_button_buy_all);
        tvMyShare.setTextColor(Color.parseColor("#FFFFFF"));
        tvShare.setBackground(null);
        tvShare.setTextColor(Color.parseColor("#353535"));
        getData();
    }

    private void getData() {
        DialogUtils.showLoadingDialog(this);
        UserInfo user = SessionManager.getDefault().getUser();
        String url = ApiConstant.BASE_URL + (chooseTab == 1 ? ApiConstant.SHARE_FOR_FREE_PROGRAM_LIST : ApiConstant.MY_SHARE_LIST + user.getId());
        OkGo.<BaseResponseBean<PageBean<ProgramDetailBean>>>get(url)
                .params("startPoint", currrentPage)
                .params("maxPage", maxPage)
                .execute(new JsonCallback<BaseResponseBean<PageBean<ProgramDetailBean>>>() {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<PageBean<ProgramDetailBean>>> response) {
                        DialogUtils.dismiss();
                        if (!"0".equals(response.body().getCode()) || response.body().getData() == null
                                || response.body().getData().getData() == null) {
                            Toast.makeText(ShareForFreeActivity.this, "获取列表信息失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        totalPages = response.body().getData().getTotalPages();
                        datas.addAll(response.body().getData().getData());
                        if (chooseTab == 1) {
                            if (shareForFreeAdapter == null) {
                                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ShareForFreeActivity.this);
                                rv.setLayoutManager(linearLayoutManager);
                                shareForFreeAdapter = new ShareForFreeAdapter(response.body().getData().getData());
                                shareForFreeAdapter.setOnItemClickListener(ShareForFreeActivity.this);
                                rv.setAdapter(shareForFreeAdapter);
                            } else {
                                shareForFreeAdapter.addDatas(response.body().getData().getData());
                            }
                        } else {
                            if (myShareAdapter == null) {
                                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ShareForFreeActivity.this);
                                rv.setLayoutManager(linearLayoutManager);
                                myShareAdapter = new MyShareAdapter(response.body().getData().getData());
                                myShareAdapter.setOnItemClickListener(ShareForFreeActivity.this);
                                rv.setAdapter(myShareAdapter);
                            } else {
                                myShareAdapter.addDatas(response.body().getData().getData());
                            }
                        }
                    }
                });
    }

    @Override
    public void onItemClick(View view, ShareForFreeAdapter.ViewName viewName, int position) {
        if (view.getId() == R.id.tv_share) {
            clickPosition = position;
            popShareDialog();
        } else {
            Intent intent = new Intent(this, ProgramDetailActivity.class);
            intent.putExtra("programId", datas.get(position).getId());
            intent.putExtra("programName", datas.get(position).getTitle());
            startActivity(intent);
        }
    }

    @Override
    public void onItemClick(View view, MyShareAdapter.ViewName viewName, int position) {
        clickPosition = position;
        if (view.getId() == R.id.tv_share_status) {
            if ("1".equals(datas.get(clickPosition).getShareStatus())) {
                popShareDialog();
            } else if ("0".equals(datas.get(clickPosition).getShareStatus())) {
                Intent intent = new Intent(this, ProgramDetailActivity.class);
                intent.putExtra("programId", datas.get(clickPosition).getId());
                intent.putExtra("programName", datas.get(clickPosition).getTitle());
                startActivity(intent);
            }
        } else if (view.getId() == R.id.tv_share_detail) {
            Intent intent = new Intent(this, ShareDetailActivity.class);
            intent.putExtra("programId", datas.get(clickPosition).getId());
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, ProgramDetailActivity.class);
            intent.putExtra("programId", datas.get(clickPosition).getId());
            intent.putExtra("programName", datas.get(clickPosition).getTitle());
            startActivity(intent);
        }
    }


    private void popShareDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_share, null);
        shareDialog = new Dialog(this, R.style.TransparentDialog);
        shareDialog.setContentView(view);
        LinearLayout llWX = shareDialog.findViewById(R.id.ll_wx);
        LinearLayout llWXMoments = shareDialog.findViewById(R.id.ll_wx_moments);
        TextView tvCancel = shareDialog.findViewById(R.id.tv_cancel);

        llWX.setOnClickListener(this);
        llWXMoments.setOnClickListener(this);
        tvCancel.setOnClickListener(this);

        Window window = shareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

        shareDialog.setCanceledOnTouchOutside(false);
        shareDialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_wx:
                shareToWx(clickPosition);
                shareDialog.dismiss();
                break;
            case R.id.ll_wx_moments:
                shareToWxMoments(clickPosition);
                shareDialog.dismiss();
                break;
            case R.id.tv_cancel:
                if (shareDialog != null) shareDialog.dismiss();
                break;
        }
    }

    private void shareToWxMoments(int clickPosition) {
        SendMessageToWX.Req req = SharePre(clickPosition);
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        TtbtApplication.wxapi.sendReq(req);
    }

    private void shareToWx(int clickPosition) {
        SendMessageToWX.Req req = SharePre(clickPosition);
        req.scene = SendMessageToWX.Req.WXSceneSession;
        TtbtApplication.wxapi.sendReq(req);
    }

    private SendMessageToWX.Req SharePre(int clickPosition) {
        if (!isWXAppInstall()) return null;

        ProgramDetailBean bean = datas.get(clickPosition);
        int programId = bean.getId();
        //记录分享记录
        addShareRecord(programId, userId);

        WXWebpageObject webPage = new WXWebpageObject();
        String url = "https://blistening.cn/ttbt_act_h5/share-detail.html"
                + "?programId=" + programId + "&srcUserId=" + userId;
        webPage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage();
        msg.title = bean.getTitle();
        msg.description = bean.getDescribe();
        msg.mediaObject = webPage;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webPage");
        req.message = msg;
        return req;
    }

    private String buildTransaction(String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();

    }

    private void addShareRecord(int programId, int userId) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("programId", programId);
        map.put("userId", userId);
        Gson gson = new Gson();
        String s = gson.toJson(map);
        OkGo.<BaseResponseBean<String>>post(ApiConstant.BASE_URL + ApiConstant.ADD_SHARE_RECORD)
                .upJson(s)
                .execute(new JsonCallback<BaseResponseBean<String>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<String>> response) {
//                        if ("0".equals(response.body().getCode())){}
                        //这里不用做任何处理
                    }
                });
    }

    private boolean isWXAppInstall() {
        if (TtbtApplication.wxapi.isWXAppInstalled()) {
            return true;
        } else {
            Toast.makeText(this, "请安装微信客户端", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}
